package com.cuanbobox.tcp.wds;


import android.util.Log;

import com.cuanbobox.activity.MainActivity;
import com.cuanbobox.base.App;
import com.cuanbobox.bean.EventBusBean;
import com.cuanbobox.bean.PPTBean;
import com.cuanbobox.bean.WdsBean;
import com.cuanbobox.bean.WdsDataList;
import com.cuanbobox.constant.CbConstant;
import com.cuanbobox.utils.BroadcastUtil;
import com.cuanbobox.utils.LogUtil;
import com.cuanbobox.utils.WdsThread;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 接收矩阵消息的线程
 */
public class WindowsReceiveThread extends Thread {
    private WindowsInitThread tcpInitThread;
    private InputStream input;
    public static long recordTime;
    private boolean loop;
    private BufferedInputStream bis;
    private String text="";

    public WindowsReceiveThread(WindowsInitThread tcpInitThread) {
        this.tcpInitThread = tcpInitThread;
        try {
            input = tcpInitThread.getSocket().getInputStream();
            bis = new BufferedInputStream(input);
        } catch (IOException e) {}
    }

    @Override
    public void run() {
        super.run();
        loop = true;
        LogUtil.add("启动", "启动接收线程-->" + Thread.currentThread().getName(), "互动TCP");
        while (App.running && loop) {
            try {
                //非阻塞接收数据，但数据大小有限制
                byte buffer[] = new byte[10240];
                int count = bis.read(buffer);
                if (count != -1) {
                    String str = new String(buffer, 0, count, "utf-8");
                    recordTime = new Date().getTime();
                    if(Pattern.matches("<.*:.*:.*:.*\\.", str)){
                        new WdsThread(str).start();
                    }else{
                        if(str.indexOf("<")==0){
                            text=str;
                        }else{
                            text+=str;
                        }
                        if(text.lastIndexOf(".")==text.length()-1){
                            new WdsThread(text).start();
                        }
                    }
                    LogUtil.add("接收数据",""+str,"互动TCP接收全部数据");
                }
            }catch (Exception e) {
                LogUtil.addError("---------------WindowsReceiveThread异常-----------------");
                LogUtil.addError(e);
                LogUtil.addError("---------------end-----------------");
                tcpInitThread.close();
            }
        }
        try {
            bis.close();
            input.close();
        } catch (IOException e) {
        }
        LogUtil.add("接收", "关闭接收线程-->" + Thread.currentThread().getName(), "互动TCP");
    }

    public void stopThread() {
        loop = false;
    }


}
